package com.cango.qutz.web.controller.job;


import com.cango.framework.base.Constants;
import com.cango.framework.base.entity.DictEntity;
import com.cango.framework.base.entity.SessionUserVo;
import com.cango.framework.base.opt.DictUtils;
import com.cango.qutz.web.auth.user.service.IUserService;
import com.cango.qutz.web.entity.ReturnVO;
import com.cango.qutz.web.entity.ScheduleExecution;
import com.cango.qutz.web.entity.ScheduleJob;
import com.cango.qutz.web.entity.ScheduleParam;
import com.cango.qutz.web.job.IScheduleDefineService;
import com.cango.qutz.web.job.IScheduleService;
import com.cango.qutz.web.auth.role.controller.RoleController;
import com.cango.framework.base.AjaxReturnVO;
import com.cango.framework.base.controller.BaseController;
import com.cango.framework.base.pagination.DataTableRequest;
import com.cango.framework.base.pagination.DataTableResponse;
import com.cango.framework.base.pagination.PageInfo;
import com.cango.framework.base.pagination.PaginationResult;
import com.cango.qutz.web.auth.role.controller.RoleController;
import com.google.gson.Gson;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 〈一句话功能简述〉<br>
 * 定时任务管理controller
 *
 * @author Yang Zhi
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Controller
@RequestMapping("/quartz")
public class TiggerController extends BaseController {
    /**
     * log
     */
    private final Log log = LogFactory.getLog(RoleController.class);

    /**
     * SERVICE层
     */
    @Autowired
    private IScheduleService scheduleService;

    @Autowired
    IScheduleDefineService scheduleDefineService;

    @Autowired
    DictUtils dictUtils;

    @Autowired
    IUserService userService;

    /**
     * 功能描述: <br>
     * 到任务管理主页面
     *
     * @return 页面
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/toJobList")
    public String toJobList(Model model) {
        model.addAttribute("appList",getAppList());
        return "trigger/jobList";
    }

    private List<DictEntity> getAppList(){
        List<DictEntity> appList = dictUtils.getDictList(90002);
        SessionUserVo user = getSessionUser();
        if(!Constants.USER_ADMINISTRATOR_CODE.equals(user.getUserType())){
            appList = userService.getUserSys(user.getUserId());
        }
        return appList;
    }



    /**
     * 功能描述: <br>
     * 到新增页面
     *
     * @return 页面
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/toJobAdd")
    public String toJobAdd(Model model,String clientCode) {
        model.addAttribute("appList",getAppList());

        return "trigger/jobAdd";
    }

    /**
     * 得到jobList
     * @param clientCode
     * @return
     */
    @RequestMapping("/getJobList")
    @ResponseBody
    public List<ScheduleJob> getJobList(String clientCode){
        return scheduleDefineService.queryAllJobDefines(clientCode);
    }
    /**
     * 获取job的参数列表
     * @param jobId
     * @return
     */
    @RequestMapping("/getPramsByJob")
    @ResponseBody
    public List<ScheduleParam> getPramsByJob(String jobId){
        return scheduleDefineService.queryParamByJob(jobId);
    }
    /**
     * 功能描述: <br>
     * 得到所有的任务
     *
     * @param job 任务信息
     * @param dataTable 表格信息
     * @return 数据
     * @throws SchedulerException 异常
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/getAllJob")
    @ResponseBody
    public DataTableResponse<ScheduleJob> getAllJob(ScheduleJob job, DataTableRequest dataTable)
            throws SchedulerException {
        PageInfo pageInfo = new PageInfo(dataTable.getCurrentPage(), dataTable.getiDisplayLength());
        SessionUserVo user = getSessionUser();
        job.setUserId(user.getUserId());
        if(Constants.USER_ADMINISTRATOR_CODE.equals(user.getUserType())){
            job.setIsAdmin("1");
        }else{
            job.setIsAdmin("0");
        }
        PaginationResult<ScheduleJob> result = this.scheduleService.getJobList(job, pageInfo);
        return new DataTableResponse<>(dataTable.getsEcho(), result);
    }


    /**
     * 功能描述: <br>
     * 到管理页面
     *
     * @param job 任务
     * @param model Model
     * @return 页面
     * @throws SchedulerException 异常
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/toJobEdit")
    public String toEdit(ScheduleJob job, Model model) throws SchedulerException {
        ScheduleJob jobInfo = this.scheduleService.queryJobByParams(job);
        model.addAttribute("job", jobInfo);
        model.addAttribute("params",scheduleService.queryParamsBySchedule(job.getScheduleId()));
        return "trigger/tiggerEdit";
    }

    /**
     * 功能描述: <br>
     * 修改任务时间
     *
     * @param job 任务信息
     * @param response 响应
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/editTiggerCron")
    public void editTiggerCron(ScheduleJob job, HttpServletResponse response) {
        String returnCode;
        try {
            returnCode = this.scheduleService.editJob(job);

            if ("errCron".equals(returnCode)) {
                super.ajaxJson(response, AjaxReturnVO.failed("时间间隔格式不正确！"));
            } else {
                log.info("用户" + getSessionUser().getUserName() + "修改了定时任务时间:" + (new Gson()).toJson(job));
                super.ajaxJson(response, AjaxReturnVO.success());
            }
        } catch (SchedulerException e) {
            log.error("编辑任务出错",e);
        }

    }

    /**
     * 功能描述: <br>
     * 停止一个job
     *
     * @param job 任务
     * @param response 响应
     * @throws SchedulerException 异常
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/stopJob")
    public void stopJob(ScheduleJob job, HttpServletResponse response) throws SchedulerException {
        this.scheduleService.updateDoStopJob(job);
        log.info("用户" + getSessionUser().getUserName() + "暂停了定时任务:" + (new Gson()).toJson(job));
        super.ajaxJson(response, AjaxReturnVO.success());
    }

    /**
     * 功能描述: <br>
     * 恢复一个任务
     *
     * @param job 任务
     * @param response 响应
     * @throws SchedulerException 异常
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/startJob")
    public void startJob(ScheduleJob job, HttpServletResponse response) throws SchedulerException {
        this.scheduleService.updateDoStartJob(job);
        log.info("用户" + getSessionUser().getUserName() + "启动了定时任务:" + (new Gson()).toJson(job));
        super.ajaxJson(response, AjaxReturnVO.success());
    }

    /**
     * 功能描述: <br>
     * 验证任务名的唯一性
     *
     * @param jobName 任务名称
     * @return 结果
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/validJobName")
    @ResponseBody
    public boolean validJobName(String jobName) {
        return this.scheduleService.validJobName(jobName);
    }

    /**
     * 功能描述: <br>
     * 新增任务
     *
     * @param job 任务信息
     * @param response 响应
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/addJob")
    public void addJob(ScheduleJob job, HttpServletResponse response,HttpServletRequest request) {
        Enumeration<String> pns= request.getParameterNames();
        Map<String,Object> param = new HashMap<String,Object>();
        while(pns.hasMoreElements()){
            String pn = pns.nextElement();
            if(!pn.startsWith("p_")){
                continue;
            }
            param.put(pn.substring(2),request.getParameter(pn));
        }
        String returnCode = this.scheduleService.insertJobAndParam(job, param);
        if ("errCron".equals(returnCode)) {
            super.ajaxJson(response, AjaxReturnVO.failed("时间间隔格式不正确！"));
        }else{
            log.info("用户" + getSessionUser().getUserName() + "新增了任务:" + (new Gson()).toJson(job));
            super.ajaxJson(response, AjaxReturnVO.success());
        }
    }


    /**
     * 功能描述: <br>
     * 删除一个任务
     *
     * @param job 任务信息
     * @param response 响应信息
     * @throws SchedulerException 异常
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/deleteJob")
    public void deleteJob(ScheduleJob job, HttpServletResponse response) throws SchedulerException{
        this.scheduleService.deleteJob(job);
        super.ajaxJson(response, AjaxReturnVO.success());
    }

    /**
     * 立即执行
     * @param scheduleId
     */
    @RequestMapping("/executeOnce")
    @ResponseBody
    public ReturnVO executeOnce(Integer scheduleId){
        ScheduleJob param=new ScheduleJob();
        param.setScheduleId(scheduleId);
        scheduleService.updateJobOnce(scheduleService.queryJobByParams(param));
        ReturnVO vo = new ReturnVO();
        vo.setStatus(HttpServletResponse.SC_OK);
        return vo;
    }

    /**
     * 跳转执行明细页面
     * @param scheduleId
     * @param model
     * @return
     */
    @RequestMapping("/toExecution")
    public String toExecutionPage(Integer scheduleId,Model model){
        ScheduleJob param = new ScheduleJob();
        param.setScheduleId(scheduleId);
        model.addAttribute("schedule", scheduleService.queryJobByParams(param));
        return "trigger/executionDetail";
    }

    /**
     * 查询执行记录
     * @param scheduleId
     * @param page
     * @param pagesize
     * @return
     */
    @RequestMapping("/getExecutionsBySid")
    @ResponseBody
    public List<ScheduleExecution> getExecutionsBySid(Integer scheduleId,int page,int pagesize){
        return scheduleService.getExecutionsBySid(scheduleId);
    }
}
